package com.jiyun.user.service.impl;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import com.jiyun.Result.Result;
import com.jiyun.Result.ResultCodeEnum;
import com.jiyun.common.pojo.home.User;
import com.jiyun.common.pojo.user.Integral;
import com.jiyun.common.pojo.user.SigninRecord;
import com.jiyun.user.mapper.IntegralMapper;
import com.jiyun.user.mapper.SigninRecordMapper;
import com.jiyun.user.service.SigninRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
//
@Transactional
@Slf4j
public class SigninRecordServiceImpl implements SigninRecordService {

    @Autowired
    private SigninRecordMapper signinRecordMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IntegralMapper integralMapper;

    /**
     * 添加签到记录
     *
     * @param date 签到日期
     * @param token 用户令牌
     * @return 添加签到记录的结果
     */
    @Override
    public Result addSigninRecord(Date date, String token) {
        //检查token是否非空
        if (token != null) {
            //根据token获取用户信息
            Object o = redisTemplate.opsForValue().get(token);
            //将用户信息转换为User对象
            User users = JSONUtil.toBean(o.toString(), User.class);
            //查询积分信息
            //date转为yyyy-MM-dd
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //转换
            String format = sdf.format(date);
            //查询签到记录
            SigninRecord signinRecords = signinRecordMapper.findSigninRecordByOne(users.getId(), format);
            //日志记录签到信息
            log.info("签到记录为：" + signinRecords);
            log.info("签到时间为：" + date);
            //检查是否存在重复签到记录
            if (signinRecords != null) {
                //已存在签到记录，返回错误信息
                return Result.build(null, ResultCodeEnum.ORDER_PRICE_ERROR);
            }
            //创建新的签到记录对象
            SigninRecord signinRecord = new SigninRecord();
            signinRecord.setUserId(users.getId());
            signinRecord.setSigninTime(date);
            //插入签到记录到数据库
            signinRecordMapper.insert(signinRecord);
            //更新用户积分
            integralMapper.update(users.getId());
            //返回签到成功结果
            return Result.build(null, ResultCodeEnum.ORDER_STOCK_FALL);
        }
        //token为空，返回未登录结果
        return Result.build(null, ResultCodeEnum.LOGIN_AUTH);
    }
}
